#version 400 core

#define POSITION	0
#define NORMAL		1
#define COLOR		2
#define TEXCOORD	3
#define FRAG_COLOR	0
#define FRAG_COLOR_AD0 1
#define FRAG_COLOR_AD1 2
#define FRAG_COLOR_AD2 3

uniform sampler2D heightSampler;
uniform ivec2 texRes;

layout(location = FRAG_COLOR) out vec4 COLOR_OUT;

in vec2 fTexcoord;
in vec3 fPos;

float gaussW(float x, float sigma2) {
    return exp(-(x/sigma2));
}

void main()
{
	//float height = texture(heightSampler, centre_coord).r; 		
	vec2 c = fTexcoord*vec2(texRes.x-1.0, texRes.y-1.0);
	c += vec2(0.5, 0.5);
	c /= texRes;
	
	//c = fTexcoord;

	float cen 	=  texture(heightSampler, fTexcoord).r; // textureOffset(heightSampler, c, ivec2(0.0, 0.0)).r; 

    int range = 10;
    float filtSum = 0.0f;
    float weightSum = 0.0f;

    for ( int i = -range; i <= range; ++i) {
        for ( int j = -range; j <= range; ++j) {
            float len = length(vec2(i,j));
            float nei = textureOffset(heightSampler, c, ivec2(i, j)).r; 

            float valW = gaussW((cen-nei)*(cen-nei), 0.05f);
            float domainW = gaussW(len*len, 0.5f);
            float weight = domainW * valW;

            filtSum += weight * nei;
            weightSum += weight;
        }
    } filtSum /= weightSum;


	COLOR_OUT = vec4(filtSum, filtSum, filtSum, 1.0);
	//COLOR_OUT = vec4(c, 0.0, 1.0);
}
